﻿using HJMinimally.Loger;
using HJMinimally.Utility.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using HJMinimally.Utility.Enums;

namespace HJMinimally.Minio.WebApi.Filter
{
    /// <summary>
    /// 全局异常过滤
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            WriteLog(context);
            context.ExceptionHandled = true;
            context.HttpContext.Response.StatusCode = 500;
            context.Result = new JsonResult(new ResParameter
            {
                code = ResponseCode.exception,
                info = ResponseCode.exception.GetEnumText(),
                data = new object { }
            });
        }
        /// <summary>
        /// 写入日志（log4net）
        /// </summary>
        /// <param name="context">提供使用</param>
        private void WriteLog(ExceptionContext context)
        {
            if (context == null)
                return;
            var description =
                 (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor;

            var Controllername = description.ControllerName;
            var Actionname = description.ActionName;

            //var log = LogFactory.GetLogger($"{Controllername}");
            Exception Error = context.Exception;
            LogMessage logMessage = new LogMessage();
            logMessage.OperationTime = DateTime.Now;
            logMessage.Url = $"{Controllername}/{Actionname}";
            logMessage.Class = $"{Controllername}";

            if (Error.InnerException == null)
            {
                logMessage.ExceptionInfo = Error.Message;
                logMessage.ExceptionSource = Error.Source;
                logMessage.ExceptionRemark = Error.StackTrace;
            }
            else
            {
                logMessage.ExceptionInfo = Error.InnerException.Message;
                logMessage.ExceptionSource = Error.InnerException.Source;
                logMessage.ExceptionRemark = Error.InnerException.StackTrace;
            }

            string strMessage = LogFormat.ExceptionFormat(logMessage);
            Log.Logger.Error(strMessage);
        }
    }
}